package com.wxp.demo06.sqlite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.wxp.demo06.R;

/**
 * 2.1 数据库管理器SQLiteDatabase
 */
public class SQLiteDatabaseActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv_database;
    private String mDatabaseName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_sqlite_database);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        this.setTitle("2.1 数据库管理器SQLiteDatabase");

        tv_database = findViewById(R.id.tv_database);
        findViewById(R.id.btn_database_create).setOnClickListener(this);
        findViewById(R.id.btn_database_delete).setOnClickListener(this);
        // 生成一个测试数据库的完整路径
        //this.getFilesDir()：/data/data/应用包名/files
        mDatabaseName = this.getFilesDir() + "/test.db";

    }

    @Override
    public void onClick(View v) {
        String desc;
        if (v.getId() == R.id.btn_database_create) {
            // 创建或打开数据库。数据库如果不存在就创建它，如果存在就打开它
            try (SQLiteDatabase db = this.openOrCreateDatabase(mDatabaseName, Context.MODE_PRIVATE, null);) {

                boolean open = db.isOpen();
                int version = db.getVersion();
                String path = db.getPath();

                desc = String.format("数据库%s创建%s", db.getPath(), (db != null) ? "成功" : "失败");
                tv_database.setText(desc
                        + "\n是否打开：" + open
                        + "\n版本号：" + version
                        + "\n路径：" + path
                );
            }
        } else if (v.getId() == R.id.btn_database_delete) {
            // 删除数据库
            boolean result = this.deleteDatabase(mDatabaseName);
            desc = String.format("数据库%s删除%s", mDatabaseName, result ? "成功" : "失败");
            tv_database.setText(desc);
        }
    }
}